<template>
	<div class="system-menu-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="menuDialogFormRef" :model="state.dataForm" size="default" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="24" class="mb20">
						<el-form-item label="上级分类">
							<el-cascader
								:options="state.parentData"
								:props="{ checkStrictly: true,emitPath:false, value: 'id', label: 'name' }"
								placeholder="选择上级分类"
								clearable
								class="w100"
								v-model="state.dataForm.parentId"
							>
								<template #default="{ node, data }">
									<span>{{ data.name }}</span>
									<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
								</template>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="分类名称">
							<el-input v-model="state.dataForm.name" placeholder="" clearable></el-input>
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="icon">
              <el-input v-model="state.dataForm.icon" clearable placeholder="配合前端页面加载的icon填写" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="12" class="mb20">
            <el-form-item label="状态">
              <el-switch v-model="state.dataForm.status" active-value="1" inactive-value="0" inline-prompt active-text="启用" inactive-text="禁用"></el-switch>
            </el-form-item>
          </el-col>
					<el-col :xs="24" :sm="6" :md="8" :lg="6" :xl="12" class="mb20">
						<el-form-item label="排序">
							<el-input-number min="0" v-model="state.dataForm.sort" controls-position="right" placeholder="越小越靠前" class="w100" />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" class="mb20">
            <el-form-item label="LOGO">
              <el-upload
                  class="avatar-uploader"
                  :action="state.uploadImgUrl"
                  :show-file-list="true"
                  :on-success="handleUploadSuccess"
                  accept="image/*"
                  :on-remove="clearValue"
                  :headers="state.header"
                  :file-list="state.fileList"
              >
                <img v-if="state.dataForm.logo" :src="state.dataForm.logo" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon" :size="30"><ele-Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Session } from "/@/utils/storage";
import {useArticleClassifyApi} from "/@/api/content/articleclassify";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const menuDialogFormRef = ref();
const baseUrl = import.meta.env.VITE_API_URL;


const state = reactive({
	dataForm: {
		parentId:0,// 上级
		name: '', // 名称
		sort: 0, // 排序
		logo:'',//logo
		icon:'',//icon
    status:'1',//状态
		id:0,//id
	},
	parentData: [], // 上级菜单数据
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	isAdd:true,//是否新增
  header:{Authorization: Session.get('token')},//上传请求头
  uploadImgUrl: baseUrl+'AdminUpload/image',//图片上传地址
  fileList: [],//文件列表
});

// 获取 pinia 中的路由
const getParentData = () => {

    useArticleClassifyApi().getAdminArticleClassifyParent().then(res => {
      state.parentData = res.data;
    }).catch(err => {
      console.log(err);
    });

};
//上传成功
const handleUploadSuccess = (
    response:any,
    uploadFile:any
) => {
  if(!response.code){
    state.dataForm.logo = response.data;
    state.fileList = [
      {name:uploadFile.name,url:response.data}
    ];
  }else{
    ElMessage.error(response.msg);
  }
}
//清除值
const clearValue = () => {
  state.dataForm.logo = '';
  state.fileList = [];
}

// 打开弹窗
const openDialog = (type: string, row?: any) => {
  getParentData();
  state.fileList = [];//清空图片列表
	if (type === 'edit') {
		let info = row;
    info.status += '';
		info = getFormData(info);
		state.dataForm = info;
    if(state.dataForm.logo){
       state.fileList = [
         {name: info.logo.substring(info.logo.lastIndexOf('/')+1), url: info.logo}
       ];
    }

		state.dialog.title = '修改分类';
		state.dialog.submitTxt = '修 改';
		state.isAdd = false;
	} else {
		state.dialog.title = '新增分类';
		state.dialog.submitTxt = '新 增';
		// 清空表单
		state.dataForm = {
      parentId: row?row.id:0,// 上级
      name: '', // 名称
      sort: 0, // 排序
      logo:'',//logo
      icon:'',//icon
      status:'1',//状态
      id:0,//id
    };
		state.isAdd = true;
	}

	state.dialog.type = type;
	state.dialog.isShowDialog = true;

};
//填充提交数据
const getFormData = (data: any) => {
	let newData = {} as any,i;
	for(i in state.dataForm){
		newData[i] = data[i];
	}

	return newData;
}
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = () => {
  useArticleClassifyApi().setAdminArticleClassify(state.dataForm).then(res=>{
		if(!res.code){
      // 清空表单
      state.dataForm = {
        parentId:0,// 上级菜单
        name: '', // 名称
        sort: 0, // 排序
        logo:'',//logo
        icon:'',//icon
        status:'1',//状态
        id:0,//id
      };
			ElMessage.success(state.dialog.title+'成功');
      closeDialog(); // 关闭弹窗
      emit('refresh');
		}
	}).catch(err=>{
		console.log(err);
	})

};
// 页面加载时
onMounted(() => {
  //getParentData();
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 30px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.video{
  width:300px;
  height: 180px;
  background-color: #000000;
}
.uploader-btn-box{
  margin-left: 20px;
}
.file-uploader{
  width:60%;
}
</style>
